import NProgress from 'nprogress';
import store from '@/store';
import router from '@/router';
import CONST from '@/utils/Const';
NProgress.inc(0.2);
NProgress.configure({ easing : 'ease', speed : 500, showSpinner : false });

const whiteList = ['/login'];
router.beforeEach(async (to, from, next) => {
	document.title = to.meta && to.meta.title || 'admin';
	store.commit('AxiosCancel/'+CONST.AXIOS_CLEAR_QUEUE);
	NProgress.start();
	if (whiteList.some(v => v === to.path)) {
		next();
	} else if (!store.getters['User/user'].userId) {
		NProgress.done();
		next(`/login?redirect=${to.path}`);
	} else {
		if (store.getters['Menu/treeList'].length === 0) {
			const accessRoutes = await store.dispatch('Menu/treeAction');
			router.addRoutes(accessRoutes);
			router.addRoutes([
				{
					path : '*',
					redirect : '/home'
				}
			]);
			next({ ...to });
		} else {
			next();
		}
	}
});

router.afterEach(() => {
	NProgress.done();
});
